/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.dao.ibatis;

import java.util.List;

import org.geoscheduler.dao.TokenDAO;
import org.geoscheduler.model.Token;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;

/**
 * Data access object for handling {@link Token}s.
 *
 * @author srakyi
 */
public class SqlMapTokenDAO extends SqlMapAbstractDAO implements TokenDAO {

	/**
	 * @see org.geoscheduler.dao.BasicGSDAO#insert(java.lang.Object)
	 */
	public Token insert(Token entity) throws DataAccessException {
		getSqlMapClientTemplate().insert("insertToken", entity);
		return entity;
	}

	/**
	 * @see org.geoscheduler.dao.BasicGSDAO#delete(java.lang.Object)
	 */
	@Transactional()
	public int delete(String id) throws DataAccessException {
		return getSqlMapClientTemplate().delete("deleteTokenById", id);
	}

	/**
	 * @see org.geoscheduler.dao.BasicGSDAO#loadById(java.lang.Object)
	 */
	public Token loadById(String id) throws DataAccessException {
		return (Token) getSqlMapClientTemplate().queryForObject("selectTokenById", id, new Token()); 
	}
	
	/**
	 * @see org.geoscheduler.dao.TokenDAO#loadByAccountId(java.lang.Long)
	 */
	@Transactional(readOnly = true)
	@SuppressWarnings("unchecked")
	public List<Token> loadByAccountId(Long id) {
		return getSqlMapClientTemplate().queryForList("selectTokensByAccountId", id);
	}

	/**
	 * @see org.geoscheduler.dao.BasicGSDAO#update(java.lang.Object)
	 */
	public Token update(Token entity) throws DataAccessException {
		if (getSqlMapClientTemplate().update("updateToken", entity) == 1) {
			return entity;
		} else {
			return (Token)getSqlMapClientTemplate().queryForObject("selectTokenById", entity.getId());
		}
	}

}
